'''
Created on Aug 30, 2012

@author: petrina
'''

from link_indicator import Link_indicator
from indiutils import Indiutils
import logging


class Buffer_time(Link_indicator):
    '''
    Calculates the Buffer-Time for every time interval (using aggregated fcd-data).
    
    Formula for calculating the indicator: 
        bt_i = wtt_i - att_i
            where:
                - bt_i... Buffer-Time for time interval i
                - wtt ... Worst-case-traveltime  for time interval i
                - att ... average-travel time for time interval i
                
    As worst-case-traveltime the 95th percentile travel time is chosen.
    
    unit: seconds (s)
    '''


    def __init__(self, link):
        '''        
        @param link: Link-object (containing valid records and timeseries) 
        '''
        
        Link_indicator.__init__(self, link)
        self._name = 'Buffer Time'
        self._mr_name =  'buffer_time'
        self._unit = 's'
        #self.unit.__doc__ = 'seconds (s)'
        
        self._create_title(link.id, link.direction)
        
        logging.debug("Buffer_time: created new Buffer_time")
        
    #----------------------public methods of the class-------------------------

    def calculate(self):
        '''
        @return: buffer time for every time interval as list of Result_values
        '''
        
        logging.info("Buffer_time: staring to calculate the buffer time")
        
        utils = Indiutils()
        p95 = utils.p95_tt(self._link.timeseries, self._link.length)
        att = utils.calc_average_of(self._link.records, "traveltime")
        
        self._values = []
        # build the buffer time for every time interval
        for i in range(self._intervals):
            # treat empty lists (= no measurement)
            value = p95[i] - att[i] if p95[i] is not None and att[i] is not None else None
            self._values.append(value)
        
        logging.debug("Buffer_time: finished calculating the buffer time")

        return self._values